package com.nashuju.web.service.role;

import java.util.ArrayList;
import java.util.List;

import org.durcframework.core.expression.Expression;
import org.durcframework.core.expression.ExpressionQuery;
import org.durcframework.core.expression.subexpression.InnerJoinExpression;
import org.durcframework.core.expression.subexpression.ValueExpression;
import org.durcframework.core.service.CrudService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nashuju.web.dao.role.RoleDao;
import com.nashuju.web.entity.role.DataPermission;
import com.nashuju.web.entity.role.Role;
import com.nashuju.web.entity.sys.SysFunction;

@Service
public class RoleService extends CrudService<Role, RoleDao> {

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RolePermissionService permissionService;

    public void addRole(Role role, List<Integer> sfIds) {
        this.save(role);

        if (role.getRoleId() > 0) {
            permissionService.setSysFunctionRole(sfIds, role.getRoleId());
        }
    }

    public void updateRole(Role role, List<Integer> sfIds) {
        this.update(role);

        if (role.getRoleId() > 0) {
            permissionService.setSysFunctionRole(sfIds, role.getRoleId());
        }
    }

    /**
     * 返回系统功能分配的角色
     * @param sysFunction
     * @return
     */
    public List<Role> getRolesBySysFunction(SysFunction sysFunction) {
        return this.getDao().findRoleByFunction(sysFunction.getSfId());
    }

    /**
     * 删除角色 先删除管理表信息,再删除自身
     */
    @Override
    public void del(Role entity) {
        userRoleService.delByRoleId(entity.getRoleId());
        permissionService.delByRoleId(entity.getRoleId());
        this.getDao().del(entity);
    }

    /**
     * 获取用户数据权限对应的角色
     * @param dpId
     * @return
     */
    public List<Role> getDataPermissionRole(DataPermission entity) {
        ExpressionQuery query = ExpressionQuery.buildQueryAll();

        query.add(new InnerJoinExpression("r_data_permission_role", "t2", "role_id", "role_id"));

        query.add(new ValueExpression("t2.dp_id", entity.getDpId()));

        return this.find(query);
    }


    /**
     * 获取用户的角色
     * @param username
     * @return
     */
    public List<Role> getUserRole(String username) {
        List<Expression> expres = new ArrayList<Expression>();
        expres.add(new InnerJoinExpression("r_user_role", "t2", "role_id", "role_id"));
        expres.add(new ValueExpression("t2.username", username));

        ExpressionQuery query = ExpressionQuery.buildQueryAll();
        query.addAll(expres);

        return this.find(query);
    }

}
